import type { HoldItem } from '@/indexDB/initHold'
import type { HoldHistoryItem } from '@/indexDB/initHistory'

import dayjs from 'dayjs'
import { DATE_FORMAT } from '@/utils/time'

self.addEventListener('message', e => {
  const { historyList, holdList } = JSON.parse(e.data)
  const list = getTimeHoldList(historyList, holdList)
  postMessage(list)
})

const getHistorySortedByTime = (list: HoldHistoryItem[]) => {
  return list.sort((a, b) => +a.createTime - +b.createTime)
}

const getTimeList = (list: HoldHistoryItem[]) => {
  const temp = getHistorySortedByTime(list).map((history) =>
    dayjs(+history.createTime).format(DATE_FORMAT)
  )
  return [...new Set(temp)]
}

const getTimeHoldList = (historyList: HoldHistoryItem[], holdList: HoldItem[]) => {

  const timeList = getTimeList(historyList)
  return timeList.map(time => {
    let timeValue = 0
    let timeCost = 0
    const timeHoldList = holdList.map(hold => {
      const { id } = hold
      const thisHoldHistoryList = getHistorySortedByTime(historyList.filter(each => each.holdId === id))

      const thisTimeHoldItem = thisHoldHistoryList.findLast(each => {
        const createDate = dayjs(+each.createTime).format(DATE_FORMAT)
        return time >= createDate
      }) || {} as HoldItem



      const { holdValue = 0, holdPrice = 0, holdNum = 0 } = thisTimeHoldItem
      const cost = +(holdPrice * holdNum).toFixed(2)
      timeCost += cost
      if (holdNum) {
        timeValue += Number(holdValue)

      }
      return thisTimeHoldItem || hold
    })
    const timeEarnings = +(timeValue - timeCost).toFixed(2)
    const timeEarningsPercent = +((timeEarnings / timeCost) * 100).toFixed(2)

    return {
      time,
      hold: timeHoldList,
      timeValue: +timeValue.toFixed(2),
      timeEarnings,
      timeEarningsPercent
    }
  })

}